package cn.itcast.bos.web.action.base;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.ws.rs.core.MediaType;

import org.apache.commons.lang3.StringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.serializer.SerializerFeature;

import cn.itcast.bos.domain.base.Courier;
import cn.itcast.bos.domain.base.FixedArea;
import cn.itcast.bos.domain.base.SubArea;
import cn.itcast.bos.service.base.CourierService;
import cn.itcast.bos.service.base.FixedAreaService;
import cn.itcast.bos.service.base.SubAreaService;
import cn.itcast.bos.web.action.common.BaseAction;
import cn.itcast.crm.domain.Customer;

@Namespace("/")
@ParentPackage("struts-default")
@Scope("prototype")
@Controller
public class FixedAreaAction extends BaseAction<FixedArea> {
	private static final long serialVersionUID = 1L;
	@Autowired
	private FixedAreaService fixedAreaService;
	@Autowired
	private CourierService courierService;
	@Autowired
	private SubAreaService subAreaService;

	// 添加定区
	@Action(value = "fixedArea_add", results = {
			@Result(name = "success", location = "./pages/base/fixed_area.html", type = "redirect") })
	public String add() {
		fixedAreaService.add(model);
		return SUCCESS;
	}

	// 删除定区
	private String idsStr;

	public void setIdsStr(String idsStr) {
		this.idsStr = idsStr;
	}

	@Action(value = "fixedArea_del", results = {
			@Result(name = "success", location = "./pages/base/fixed_area.html", type = "redirect") })
	public String del() {
		fixedAreaService.del(idsStr);
		return SUCCESS;
	}

	// 查询所有
	@Action(value = "fixedArea_findAll")
	public void findAll() throws IOException {
		List<FixedArea> list = fixedAreaService.findAll();
		String jsonString = JSONArray.toJSONString(list, SerializerFeature.DisableCircularReferenceDetect);
		ServletActionContext.getResponse().setContentType("application/json;charset=utf-8");
		ServletActionContext.getResponse().getWriter().write(jsonString);
	}

	// 带条件分页查询
	@Action(value = "fixedArea_pageQuery")
	public void pageQuery() throws IOException {
		// 构造分页对象
		Pageable pageable = new PageRequest(page - 1, rows);
		// 构造条件对象
		Specification<FixedArea> specification = new Specification<FixedArea>() {
			List<Predicate> list = new ArrayList<Predicate>();

			@Override
			public Predicate toPredicate(Root<FixedArea> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				// 构造查询条件
				if (StringUtils.isNotBlank(model.getId())) {
					// 根据 定区编号查询 等值
					Predicate p1 = cb.equal(root.get("id").as(String.class), model.getId());
					list.add(p1);
				}
				if (StringUtils.isNotBlank(model.getCompany())) {
					// 根据公司查询 模糊
					Predicate p2 = cb.like(root.get("company").as(String.class), "%" + model.getCompany() + "%");
					list.add(p2);
				}

				return cb.and(list.toArray(new Predicate[0]));
			}
		};
		Page<FixedArea> pageData = fixedAreaService.pageQuery(specification, pageable);
		pageDataJsonToWeb(pageData);
	}

	// webservice查询已经关联选择定区的客户
	@Action(value = "fixedArea_findHasAssociationFixedAreaCustomers")
	public void findHasAssociationFixedAreaCustomers() throws IOException {
		// create 建立与服务器资源路径的连接
		// type 发送给服务器的数据格式
		// accept 接收服务器端响应数据格式
		// getCollection 响应的数据格式
		Collection<? extends Customer> collection = WebClient
				.create("http://localhost:9090/crm_management/services/customerService/hasAssociationFixedAreaCustomers/"
						+ model.getId())
				.accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_JSON).getCollection(Customer.class);

		String jsonString = JSONArray.toJSONString(collection, SerializerFeature.DisableCircularReferenceDetect);
		ServletActionContext.getResponse().setContentType("application/json;charset=utf-8");
		ServletActionContext.getResponse().getWriter().write(jsonString);
	}

	// webservice查询没有关联定区的客户
	@Action(value = "fixedArea_findNoAssociationCustomers")
	public void findNoAssociationCustomers() throws IOException {
		Collection<? extends Customer> collection = WebClient
				.create("http://localhost:9090/crm_management/services/customerService/noAssociationCustomers")
				.accept(MediaType.APPLICATION_JSON).getCollection(Customer.class);
		String jsonString = JSONArray.toJSONString(collection, SerializerFeature.DisableCircularReferenceDetect);
		ServletActionContext.getResponse().setContentType("application/json;charset=utf-8");
		ServletActionContext.getResponse().getWriter().write(jsonString);
	}

	// 关联客户到指定定区

	// 接收在已关联到选择定区的客户ID的字符串
	private String[] customerIds;

	public void setCustomerIds(String[] customerIds) {
		this.customerIds = customerIds;
	}

	@Action(value = "fixedArea_associationCustomersToFixedArea", results = {
			@Result(name = "success", location = "./pages/base/fixed_area.html", type = "redirect") })
	public String associationCustomersToFixedArea() {
		String customerIdsStr = StringUtils.join(customerIds, ",");
		WebClient
				.create("http://localhost:9090/crm_management/services/customerService/associationCustomersToFixedArea?customerIdStr="
						+ customerIdsStr + "&fixedAreaId=" + model.getId())
				.put(null);
		return SUCCESS;
	}

	// 关联快递员到指定定区和收派时间

	// 接受表单参数(隐藏属性fixedAreaId封装在model中)
	private Integer courierId;
	private Integer takeTimeId;

	public void setCourierId(Integer courierId) {
		this.courierId = courierId;
	}

	public void setTakeTimeId(Integer takeTimeId) {
		this.takeTimeId = takeTimeId;
	}

	@Action(value = "fixedArea_associationCourierToFixedArea", results = {
			@Result(name = "success", location = "./pages/base/fixed_area.html", type = "redirect") })
	public String associationCourierToFixedArea() {
		fixedAreaService.associationCourierToFixedArea(model, courierId, takeTimeId);
		return SUCCESS;
	}

	// 通过定区id来查找快递员
	@Action(value = "fixedArea_findCourierByFixedAreaId")
	public void findCourierByFixedAreaId() throws IOException {
		String FixedAreaId = model.getId();
		List<Courier> list = courierService.findCourierByFixedAreaId(FixedAreaId);
		String jsonString = JSONArray.toJSONString(list, SerializerFeature.DisableCircularReferenceDetect);
		ServletActionContext.getResponse().setContentType("application/json;charset=utf-8");
		ServletActionContext.getResponse().getWriter().write(jsonString);
	}

	// 通过定区id来查找分区
	@Action(value = "fixedArea_findSubAreaByFixedAreaId")
	public void findSubAreaByFixedAreaId() throws IOException {
		String FixedAreaId = model.getId();
		List<SubArea> list = subAreaService.findSubAreaByFixedAreaId(FixedAreaId);
		String jsonString = JSONArray.toJSONString(list, SerializerFeature.DisableCircularReferenceDetect);
		ServletActionContext.getResponse().setContentType("application/json;charset=utf-8");
		ServletActionContext.getResponse().getWriter().write(jsonString);
	}
}
